function [x1 , globalBestFitness] = NSDE(x,popsize, maxIteration,dim, LB, UB, CR, Fun)
% 种群的初始化和计算适应度值
Sol(popsize, dim) = 0; % Declare memory.
Fitness(popsize) = 0;
for i = 1:popsize
    Sol(i,:) = LB+(UB-LB).* rand(1, dim);
    for i0 = 1 : dim
        ind = ((i0 - 1) * (size(x,2) / dim) + 1) : i0 * (size(x,2) / dim);
        x(1,ind) = x(1,ind) .* Sol(i,i0);
    end
    Fitness(i) = Fun(x(1,:));
end

% 获得全局最优值以及对应的种群向量
[fbest, bestIndex] = min(Fitness);
globalBest = Sol(bestIndex,:); 
globalBestFitness = fbest; 

% 开始迭代
for time = 1:maxIteration
    for i = 1:popsize
        % 突变
        r = randperm(popsize, 3);  %在1~pop中随机选择5个数组成一个数组
        r1 = rand();
        if r1 > 0.5
            pd = makedist('tLocationScale','mu',0,'sigma',1,'nu',1);
            F = random(pd,1,1);%生成1个柯西随机数
        else
            F = normrnd(0.5,0.5);%生成1个高斯随机数
        end
        mutantPos = Sol(r(1),:) + F * (Sol(r(2),:) - Sol(r(3),:));
        
        % 交叉
        jj = randi(dim);  % 选择至少一维发生交叉
        for d = 1:dim
            if rand() < CR || d == jj
                crossoverPos(d) = mutantPos(d);
            else
                crossoverPos(d) = Sol(i,d);
            end
        end
        
        % 检查是否越界.
        crossoverPos(crossoverPos>UB) = UB; 
        crossoverPos(crossoverPos<LB) = LB;
        
        for i1 = 1 : dim
            ind = ((i1 - 1) * (size(x,2) / dim) + 1) : i1 * (size(x,2) / dim);
            x(1,ind) = x(1,ind) .* crossoverPos(1,i1);
        end
        evalNewPos = Fun(x(1,:));% 将突变和交叉后的变量重新评估
        % 小于原有值就更新
        if evalNewPos < Fitness(i)
            Sol(i,:) = crossoverPos;
            Fitness(i) = evalNewPos;
        end
    end
    [fbest, bestIndex] = min(Fitness);
    globalBest = Sol(bestIndex,:);
    for i2 = 1 : dim
        ind2 = ((i2 - 1) * (size(x,2) / dim) + 1) : i2 * (size(x,2) / dim);
        x(1,ind) = x(1,ind2) .* globalBest(1,i2);
    end
    globalBestFitness = fbest;
    x1 = x(1,:);
end
end